package 动态数组;

public class ArrayList {
	private int size;
	private int[] elements;
	private static final int DEFAULT_CAPACITY = 10;
	private static final int ELEMENT_NOT_FOUND = -1;
	
	public ArrayList(int capacity) {
		capacity = (capacity < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : capacity;
		elements = new int[capacity];
	}
	public ArrayList() {
		this(DEFAULT_CAPACITY);
	}
	
	// 1.数组的大小
	public int size() {
		return size;
	}
	// 2.数组是否为空
	public boolean isEmpty() {
		return size == 0;
	}
	
	// 3. 清空数组
	public void clear() {
		for(int i = 0; i < size; i++) {
			elements[i] = 0;
		}
		size = 0;
	}
	
	// 4. 是否包含某个元素
	public boolean contains(int element) {
		return indexOf(element) != ELEMENT_NOT_FOUND;
	}
	
	// 5. 查看元素的索引
	public int indexOf(int element) {
		for(int i = 0; i< size; i++) {
			if(element == elements[i]) {
				return i;
			}
		}
		return ELEMENT_NOT_FOUND;
	}
	
	// 6. 获取index位置的元素
	public int get(int index) {
		// 判断是否越界
		rangeCheck(index);
		return elements[index];
	}
	
	// 7.设置index位置的元素
	public int set(int index, int element) {
		rangeCheck(index);
		
		int old = elements[index];
		elements[index] = element;
		return old;
	}
	
	// 8. 添加元素到尾部
	public void add(int element) {
		add(size, element);
	}
	// 9. 在index位置插入一个元素
	public void add(int index, int element) {
		rangeCheckForAdd(index);
		ensureCapacity(size+1);
		
		for(int i = size; i > index; i--) {
			elements[i] = elements[i-1];
		}
		elements[index] = element;
		size++;
	}
	
	// 10. 删除index位置的元素
	// @param index
	// @return
	
	public int remove(int index) {
		rangeCheck(index);
		int old = elements[index];
		for(int i = index+1; i < size; i++) {
			elements[i-1] = elements[i];
		}
		elements[--size] = 0;
		
		return old;
	}
	
	private void outOfBounds(int index) {
		throw new IndexOutOfBoundsException("index = "+ index+ ", size = "+ size); 
	}
	
	private void rangeCheck(int index) {
		if(index < 0 || index >= size) {
			outOfBounds(index);
		}
	}
	
	private void rangeCheckForAdd(int index) {
		if (index < 0 || index > size) {
			outOfBounds(index);
		}
	}
	
	/**
	 * 保证要有capacity的容量
	 * @param capacity
	 */
	private void ensureCapacity(int capacity) {
		int oldCapacity = elements.length;
		if(oldCapacity >= capacity) {
			return;
		}
		
		// 扩容为原来的1.5倍
		int newCapacity = oldCapacity + (oldCapacity >> 1);
		int[] newElements = new int[newCapacity];
		for(int i = 0; i < size; i++) {
			newElements[i] = elements[i];
		}
		elements = newElements;
		System.out.println(oldCapacity+ "扩容为" + newCapacity);
	}
	
	@Override
	public String toString() {
	
		StringBuilder string = new StringBuilder();
		string.append("size = ").append(size).append(", [ ");
		
		for(int i = 0; i < size; i++) {
			if(i != 0) {
				string.append(", ");
			}
			string.append(elements[i]);
		}
		
		string.append("]");
		
		return string.toString();
		
	}
	
}
